package com.lap.permission.event.listener;

import com.lap.permission.component.Ip2AddressHelper;
import com.lap.permission.domain.entity.LoginLog;
import com.lap.permission.domain.entity.User;
import com.lap.permission.event.entity.LoginLogEvent;
import com.lap.permission.service.LoginLogService;
import com.lap.permission.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 登录日志消息监听
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class LoginLogListener {

    private final UserService userService;

    private final Ip2AddressHelper ip2AddressHelper;

    private final LoginLogService loginLogService;

    @EventListener(LoginLogEvent.class)
    public void writerLoginLog(LoginLogEvent event) {
        User user = getUser(event.getUsername());
        String address = ip2AddressHelper.getAddress(event.getIp());

        LoginLog loginLog = new LoginLog();
        loginLog.setLoginIp(event.getIp());
        loginLog.setLoginAddress(address);
        loginLog.setSuccessFlag(event.getStatusFlag());
        loginLog.setRemark(event.getRemark());
        loginLog.setTimes(event.getTimes());
        loginLog.setBrowser(event.getDevice().getBrowser());
        loginLog.setSysInfo(event.getDevice().getOperatingSystem());
        loginLog.setUserId(user.getId());
        loginLog.setUsername(user.getUsername());
        loginLog.setFullName(user.getFullName());

        try {
            loginLogService.insertLoginLog(loginLog);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
    }

    private User getUser(String username) {
        if (StringUtils.isBlank(username)) {
            return getNull(username);
        } else {
            User user = userService.queryByUsername(username);
            return Optional.ofNullable(user).orElse(getNull(username));
        }
    }

    private User getNull(String username) {
        User user = new User();
        user.setId(0);
        user.setUsername(username);
        user.setFullName("-");
        return user;
    }

}
